package mo.tags.stack;

import mo.leetcode_top.L341_NestedIterator;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class L385 {

    public NestedInteger deserialize(String s) {
        if (s.charAt(0) != '[') {
            return new NestedInteger(Integer.parseInt(s));
        }
        Stack<NestedInteger> stack = new Stack<>();
        int start = 1;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '[') {
                stack.push(new NestedInteger());
                start = i + 1;
            } else if (s.charAt(i) == ']' || s.charAt(i) == ',') {
                if (i > start) {
                    stack.peek().add(new NestedInteger(Integer.parseInt(s.substring(start, i))));
                }
                start = i + 1;
                if (s.charAt(i) == ']' && stack.size() > 1) {
                    NestedInteger pop = stack.pop();
                    stack.peek().add(pop);
                }
            }
        }
        return stack.peek();
    }


    public static void main(String[] args) {
        L385 test = new L385();
        System.out.println(test.deserialize("[123,[456,[789]]]"));
    }


    private class NestedInteger {

        private Integer val;
        private List<NestedInteger> nestedIntegers = new ArrayList<>();

        public NestedInteger() {

        }

        public NestedInteger(int value) {
            this.val = value;
        }

        public boolean isInteger() {
            return val != null && nestedIntegers.size() == 0;
        }

        public Integer getInteger() {
            return val;
        }

        public void setInteger(int value) {
            this.val = value;
        }

        public void add(NestedInteger ni) {
            nestedIntegers.add(ni);
        }

        public List<NestedInteger> getList() {
            return nestedIntegers;
        }

    }

}
